package org.qhhc.functioninterface;

import java.util.function.Consumer;
import java.util.function.Supplier;

public class SupplierAndConsumerTest {
    public static void main(String[] args) {
        // ================== Supplier 示例 ==================
        // 1. 生成随机6位验证码（延迟生成）
        Supplier<String> randomCodeSupplier = () -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                sb.append((char) ('A' + Math.random() * 26));
            }
            return sb.toString();
        };
        System.out.println("验证码生成: " + randomCodeSupplier.get()); // 类似"QZTFME"

        // 2. 延迟加载大对象（参考网页6防御性编程场景）
        Supplier<HeavyResource> heavyResourceSupplier = () -> {
            System.out.println("-- 正在创建大对象 --");
            return new HeavyResource("DB连接池");
        };
        System.out.println("已定义Supplier，未实际创建对象");
        heavyResourceSupplier.get(); // 实际使用时才会创建

        // ================== Consumer 示例 ==================
        // 1. 基础消费：打印处理
        Consumer<String> printConsumer = System.out::println;
        printConsumer.accept("Hello Consumer"); // 直接输出字符串

        // 2. 链式操作：转大写→添加后缀（参考网页9的andThen用法）
        Consumer<String> upperCaseConsumer = s ->
                System.out.print(s.toUpperCase() + " -> ");
        Consumer<String> suffixConsumer = s ->
                System.out.println(s + "_processed");

        upperCaseConsumer.andThen(suffixConsumer).accept("test");
        // 输出：TEST -> test_processed

        // 3. 对象属性修改（参考网页11的用户对象处理）
        Consumer<User> userConsumer = user -> {
            user.setName(user.getName() + "_modified");
            user.setAge(user.getAge() + 1);
        };
        User user = new User("John", 30);
        userConsumer.accept(user);
        System.out.println("修改后用户: " + user); // John_modified,31
    }

    // 辅助类定义
    static class HeavyResource {
        private String name;
        public HeavyResource(String name) { this.name = name; }
    }

    static class User {
        private String name;
        private int age;
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        // 省略getter/setter
        @Override
        public String toString() {
            return name + "(" + age + ")";
        }
    }
}